package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.internal.CustomizerRegistry;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //参数检查
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        Page<ApUserRealname> page = new Page<>();
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> resultPage = page(page, lambdaQueryWrapper);
        //返回结果

        return new PageResponseResult(dto.getPage(),dto.getSize(),resultPage.getTotal(),resultPage.getRecords());
    }

    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 根据状态进行审核
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //参数检查
        if (dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户id不能为空");
        }
        //查看当前认证用户是否在app端有当前用户
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户信息不存在");
        }
        //查看当前用户的状态是否是待审核状态
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证信息为非待审核状态");
        }
        // 根据是哪个认证关联的userid，查询出apUser
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"未发现该实名认证关联的apuser信息");
        }
        //修改实名认证的状态
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMsg());
        this.updateById(apUserRealname);
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //开通自媒体账户
            WmUser wmUser = createWmuser(apUser);
            //创建作者信息
            createAuthor(wmUser,apUser);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleFeign articleFeign;
    /**
     * 远程创建作者信息
     */
    private void createAuthor(WmUser wmUser, ApUser apUser) {
        //先根据apUserId远程查询作者信息
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //判断作者信息是否存在，
        ApAuthor apAuthor = result.getData();

        //如果存在，则提示作者信息已存在
        if (apAuthor!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"作者信息已经存在，创建失败");
        }
        //如果不存在，则创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        articleFeign.save(apAuthor);
    }

    @Autowired
    private WemediaFeign wemediaFeign;
    /**
     *  远程开通自媒体账户
     */
    private WmUser createWmuser(ApUser apUser) {
        // 根据用户名远程查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        //如果有该用户则抛出异常，自媒体账户已存在
        if (wmUser!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自媒体用户已经存在，开通失败");
        }
        //如果没有，则新建自媒体账户并保存
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (!saveResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();
    }
































}
